package com.yonyou.gmcc.gateway.web.util;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.yonyou.gmcc.gateway.web.consts.CommonConstants;
import com.yonyou.gmcc.gateway.web.entity.UserEntity;
import com.yonyou.gmcc.gateway.web.jwt.JwtHelper;

import io.jsonwebtoken.Claims;


public class CookieUtil {
	private static Logger logger=Logger.getLogger(CookieUtil.class);

	public static void writeToken(String value, HttpServletResponse response){
		String oxid=value+",,"+new Date().toString();
		try {
			reponseCookies(CommonConstants.USER_COOKIE_NAME,
					oxid,
			    	    response);
		} catch (Exception e) {
			logger.info("---存储cookie openid出错："+e.getMessage());
			e.printStackTrace();
		}
	}
	public static String getToken(HttpServletRequest request){
		String value="";
		try {
			value = getCookiesByKey(request,CommonConstants.USER_COOKIE_NAME);
			if(value==null || "".equals(value)){
				logger.info("---cookie中的token为空!");
			}
	    	return value;
		} catch (Exception e) {
			logger.info("---取得cookie中的token出错："+value+","+e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
	
    public static UserEntity getHeadUserInfo(HttpServletRequest request)  {
    	UserEntity user=new UserEntity();
    	
    	String token=request.getHeader(CommonConstants.USER_COOKIE_NAME);
		logger.info("---header中的token="+token);
		Claims claims=JwtHelper.parseJWT(token);
		if(claims==null)
			return null;
    	user.setToken(token);
		user.setUserId(JwtHelper.getUserId(claims));
		user.setUserName(JwtHelper.getUserName(claims));
    	return user;
      }
	
    public static UserEntity getCookieUserInfo(HttpServletRequest request)  {
    	UserEntity user=new UserEntity();
    	String token=CookieUtil.getToken(request);
		Claims claims=JwtHelper.parseJWT(token);
		if(claims==null)
			return null;
    	user.setToken(token);
		user.setUserId(JwtHelper.getUserId(claims));
		user.setUserName(JwtHelper.getUserName(claims));
    	return user;
      }

    private static void reponseCookies(String key, String value, HttpServletResponse response) throws Exception {
        Cookie cookies = new Cookie(key,value);
		cookies.setMaxAge(12*60*60);//12小时有效期
        cookies.setPath("/");
        response.addCookie(cookies);
    }

    private static String getCookiesByKey(HttpServletRequest request,String key) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for(Cookie cookie : cookies) {
    			logger.info("---cookie 名称："+cookie.getName());
                if(key.equals(cookie.getName())) {
                     return cookie.getValue();
                }
            }
        }
        return null;
    }
}
